package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjFactoryAccountRole;
import com.zb.mapper.ZjFactoryAccountRoleMapper;
import com.zb.service.ZjFactoryAccountRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 厂商账号角色表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-02-27
 */
@Service
public class ZjFactoryAccountRoleServiceImpl extends ServiceImpl<ZjFactoryAccountRoleMapper, ZjFactoryAccountRole> implements ZjFactoryAccountRoleService {

    // 保存更新品牌厂商超级管理员
    @Override
    public void saveFactoryAdmin(Long factoryId, Long accountId, Long roleId) {
        QueryWrapper<ZjFactoryAccountRole> wrapper = new QueryWrapper<>();
        wrapper.select("id", "factory_account_id")
                .eq("factory_id", factoryId).eq("is_admin", true);
        ZjFactoryAccountRole accountRole = this.getOne(wrapper);
        if (null == accountRole) {
            accountRole = new ZjFactoryAccountRole();
            accountRole.setId(IdWorker.getId());
            accountRole.setFactoryId(factoryId);
            accountRole.setFactoryAccountId(accountId);
            accountRole.setFactoryRoleId(roleId);
            accountRole.setAdmin(true);
            this.save(accountRole);
            return;
        }
        // 判断超管是否同一账号
        if (Objects.equals(accountRole.getFactoryAccountId(), accountId)) {
            return;
        }
        // 查询账号已关联角色
        wrapper = new QueryWrapper<>();
        wrapper.select("id", "factory_account_id", "factory_role_id")
                .eq("factory_id", factoryId).eq("factory_account_id", accountId);
        ZjFactoryAccountRole one = this.getOne(wrapper);

        List<ZjFactoryAccountRole> updates = new ArrayList<>();
        if (null != one) {
            // 把超管的角色ID设置为非超管的角色ID
            accountRole.setFactoryRoleId(one.getFactoryRoleId());
            updates.add(accountRole);
            // 设置为超管角色ID
            one.setFactoryRoleId(roleId);
            updates.add(one);
        } else {
            accountRole.setFactoryAccountId(accountId);
            updates.add(accountRole);
        }
        this.updateBatchById(updates);
    }
}
